<?php


namespace api\zmt\controller;


use api\zmt\model\OrderModel;
use api\zmt\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
//账户余额支付
    public function walletPay(Request $request){
        $orderId = input('post.order_id');
        $order = OrderModel::find($orderId);
        if(!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] != 0){
            $this->error('订单已支付');
        }
        //查询用户
        $user = UserModel::find($request->userId);
        //判断用户余额是否够用
        if($user['wallet'] < $order['total_price']){
            $this->error('余额不足');
        }
        Db::startTrans();
        $updateOrderStatus = false;
        $addMoneyLog = false;
        $updateUserWallet = false;
        try {
            //订单的status修改成1
            $order->status = 1;
            $order->pay_type = '账户余额';
            $updateOrderStatus = $order->save();
            //流水记录
            $addMoneyLog = add_money_log($order['user_id'],$order['total_price'],'下单',$user['wallet'],'2');
            //扣除账户余额
            $updateUserWallet = UserModel::where('id',$order['user_id'])->dec('wallet',$order['total_price'])->update();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error('支付失败');
        }
        if ($updateOrderStatus && $addMoneyLog && $updateUserWallet){
            Db::commit();
            $this->success('支付成功');
        }else{
            Db::rollback();
            $this->error('支付失败');
        }
    }
}
